package com.tuteng.administrator.ashospital;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tuteng.administrator.ashospital.Activity.AddFriendactivity;
import com.tuteng.administrator.ashospital.Activity.Lis_JydjActivity;
import com.tuteng.administrator.ashospital.Activity.MannageFriendActivity;
import com.tuteng.administrator.ashospital.Activity.UserRegisterActivity;
import com.tuteng.administrator.ashospital.Activity.testActivity;
import com.tuteng.administrator.ashospital.AdapterManger.ItemAdapter;
import com.tuteng.administrator.ashospital.AdapterManger.NumberListAdapter;
import com.tuteng.administrator.ashospital.Dialog.CommomDialog;
import com.tuteng.administrator.ashospital.Dialog.CommomListDialog;
import com.tuteng.administrator.ashospital.Dialog.MenuPop;
import com.tuteng.administrator.ashospital.application.hospitalAppication;
import com.tuteng.administrator.ashospital.beans.FriendInfoBean;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by 黄启位 2017/12/9.
 */

public class OneFragment extends Fragment implements View.OnClickListener {
    @Nullable
    private ViewPager viewPager; // android-support-v4中的滑动组件
    private List<ImageView> imageViews; // 滑动的图片集合
    private String[] titles; // 图片标题
    private int[] imageResId; // 图片ID
    private List<View> dots; // 图片标题正文的那些点
    private int currentItem = 0; // 当前图片的索引号
    private Context contex;
    private PopupWindow popupWindow;
    private List<FriendInfoBean> list;
    private NumberListAdapter adapter;
    private MenuPop menuPop;
    private View view_line;
    //绑卡
    private RelativeLayout mBangka;
    //管理就诊人
    private RelativeLayout mManageCard;
    //检验查询
    private  RelativeLayout mLisChaxun;
    //检查查询
    private  RelativeLayout mJCchaxun;

    private hospitalAppication  app;
    // An ExecutorService that can schedule commands to run after a given delay,
    // or to execute periodically.
    private ScheduledExecutorService scheduledExecutorService;
    // 切换当前显示的图片
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
        }

        ;
    };


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.main_2,container,false);
        contex = container.getContext();

        /**
        TextView content= (TextView) view.findViewById(R.id.content);
        content.setText("首页"); **/
        initView(view);
        return view;
    }
/**初始化界面**/
    private void initView(View view) {

      app=hospitalAppication.getInstance();
        imageResId = new int[]{R.mipmap.imc_yysy, R.mipmap.p2, R.mipmap.p3};

       mBangka=view.findViewById(R.id.re_mian_bangka);

        mBangka.setOnClickListener(this);
        mManageCard=view.findViewById(R.id.re_manage_card);
        mManageCard.setOnClickListener(this);
        imageViews = new ArrayList<ImageView>();
        mLisChaxun=view.findViewById(R.id.re_lis_get);
        mLisChaxun.setOnClickListener(this);

        mJCchaxun=view.findViewById(R.id.re_jc_report);
        mJCchaxun.setOnClickListener(this);
        // 初始化图片资源
        for (int i = 0; i < imageResId.length; i++) {
            ImageView imageView = new ImageView(contex);
            imageView.setImageResource(imageResId[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageViews.add(imageView);
        }
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.v_dot0));
        dots.add(view.findViewById(R.id.v_dot1));
        dots.add(view.findViewById(R.id.v_dot2));


        viewPager = (ViewPager) view.findViewById(R.id.mainViewpager);
        viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
        // 设置一个监听器，当ViewPager中的页面改变时调用
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
    }

    @Override
    public void onClick(View v) {
  switch (v.getId()){
      //绑定就诊卡
      case R.id.re_mian_bangka:
          Intent intent = new Intent(contex,AddFriendactivity.class);
          contex.startActivity(intent);
          break;
          //管理就诊人
      case R.id.re_manage_card:
          Intent intent1 = new Intent(contex, MannageFriendActivity.class);
          contex.startActivity(intent1);
          break;
          //获取患者检验信息
      case   R.id.re_lis_get:
          list=app.getResponse().getFriendsInfo();
          if(list==null||list.isEmpty()){
new CommomDialog(contex,R.style.dialog,"您还没有添加就诊人，是否现在添加？", new CommomDialog.OnCloseListener() {
    @Override
    public void onClick(Dialog dialog, boolean confirm) {
        if(confirm){
            Toast.makeText(contex,"点击确定", Toast.LENGTH_SHORT).show();
            goToActivity(contex,AddFriendactivity.class);
            dialog.dismiss();
        }
    }
}).setTitle("提示").show();
        }

        else {
     new CommomListDialog(contex,R.style.dialog,list,Lis_JydjActivity.class) .setTitle("选择就诊人").show();
          }


         /**
          ItemAdapter adapter = new ItemAdapter(contex,ItemAdapter.iniDatas(app.getResponse().getFriendsInfo()));
          AlertDialog.Builder builder = new AlertDialog.Builder(contex);
          //设置标题
          builder.setTitle("请选择就诊人");

          builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialogInterface, int i) {
                 Intent intent3=new Intent();
                  intent3.setClass(contex, Lis_JydjActivity.class);
                  Bundle bundle=new Bundle();
                 bundle.putString("cardNo",app.getResponse().getFriendsInfo().get(i).getCardNo());
                 intent3.putExtras(bundle);
                  Toast.makeText(contex,"你点击的是"+i,Toast.LENGTH_SHORT).show();
                  startActivity(intent3);
              }
          });
          builder.create();
          builder.show(); **/

          break;
          //检查报告查询
        case R.id.re_jc_report:
            list=app.getResponse().getFriendsInfo();
            if(list==null||list.isEmpty()){
                new CommomDialog(contex,R.style.dialog,"您还没有添加就诊人，是否现在添加？", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if(confirm){
                            Toast.makeText(contex,"点击确定", Toast.LENGTH_SHORT).show();
                            goToActivity(contex,AddFriendactivity.class);
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示").show();
            }

            else {
                new CommomListDialog(contex,R.style.dialog,list,Lis_JydjActivity.class) .setTitle("选择就诊人").show();
            }
            break;


          default:
              break;
  }
    }


    /**
     * 填充ViewPager页面的适配器
     *
     * @author Administrator
     */
    private class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageResId.length;
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(imageViews.get(arg1));
            return imageViews.get(arg1);
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }
    }
    /**
     * 当ViewPager中页面的状态发生改变时调用
     *
     * @author Administrator
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        private int oldPosition = 0;

        /**
         * This method will be invoked when a new page becomes selected.
         * position: Position index of the new selected page.
         */
        public void onPageSelected(int position) {
            currentItem = position;
            dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dots.get(position).setBackgroundResource(R.drawable.dot_focused);
            oldPosition = position;
        }

        public void onPageScrollStateChanged(int arg0) {

        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }
    }

    /**
     * 换行切换任务
     *
     * @author Administrator
     */
    private class ScrollTask implements Runnable {

        public void run() {
            synchronized (viewPager) {
                System.out.println("currentItem: " + currentItem);
                currentItem = (currentItem + 1) % imageViews.size();
                handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
            }
        }

    }

    @Override
    public void onStart() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每两秒钟切换一次图片显示
        scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), (long) 3, 3, TimeUnit.SECONDS);
        super.onStart();
    }

    @Override
    public void onStop() {
        scheduledExecutorService.shutdown();
        super.onStop();
    }

    private void initPopWindow(Class activity){
        if (popupWindow == null) {
            // 创建一个PopupWindow对象
            // 设置PopupWindow要显示的内容
            ListView contentView = createListView(activity);
            // 设置PopupWindow的宽
            int width = 400;
            // 设置PopupWindow的高
            int height = 500;
            // 设置PopupWindow是否可以获取焦点
            boolean focusable = true;
            popupWindow = new PopupWindow(contentView, width, height, focusable);
            // 下面的两行代码是用于实现在点PopupWindow之外的地方的时候可以隐藏PopupWindow
            // 设置PopupWindow的外部可以点击
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable());
        }

        // 显示PopupWindow
        // 指定PopupWindow显示在哪个View的下方
      //  View anchor = et_number;
        // 指定PopupWindow的x方向的偏移量 xoff > 0向右偏移
        int xoff = 15;
        // 指定PopupWindow的y方向的偏移量 以et_number的底部为yoff = 0,yoff > 0向下偏移
        int yoff = -5;
        popupWindow.showAsDropDown( viewPager, 180, Gravity.CENTER_VERTICAL);
    }
    private ListView createListView(final Class activity) {
        ListView listView = (ListView) View.inflate(contex, R.layout.layout_number_list, null);

        list=app.getResponse().getFriendsInfo();
        adapter = new NumberListAdapter(contex,list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
              //  String number = (String) parent.getItemAtPosition(position);
                // et_number.setText(number);
                Intent intent3=new Intent();
                intent3.setClass(contex, activity);
                Bundle bundle=new Bundle();
                bundle.putString("cardNo",list.get(position).getCardNo());
                intent3.putExtras(bundle);
               // Toast.makeText(contex,"你点击的是"+i,Toast.LENGTH_SHORT).show();
                startActivity(intent3);
                popupWindow.dismiss();
            }
        });
        return listView;
    }

    /* activity之间跳转  */
    private void goToActivity(Context context, Class toActivity) {
        Intent intent = new Intent(context, toActivity);
        context.startActivity(intent);
    }

}